package com.wlbx.agent.ui.activity;

import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.security.keystore.KeyProperties;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.ArraySet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;
import androidx.core.os.CancellationSignal;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.bean.ServerResponse;
import com.wlbx.agent.event.RefreshHomePageEvent;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.event.UpdateUserInfoEvent;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.bean.AgentBean;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.Constants;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.fingerprint.CryptoObjectHelper;
import com.wlbx.agent.util.fingerprint.MyAuthCallback;

import org.greenrobot.eventbus.EventBus;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.KeyGenerator;
import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";

    @BindView(R.id.ll_phonelogin)
    LinearLayout ll_phone;
    @BindView(R.id.ll_pwlogin)
    LinearLayout ll_pw;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_phone_b)
    TextView tv_phone_b;
    @BindView(R.id.tv_pw)
    TextView tv_pw;
    @BindView(R.id.tv_pw_b)
    TextView tv_pw_b;
    @BindView(R.id.fl_phone)
    FrameLayout fl_phone;
    @BindView(R.id.fl_pw)
    FrameLayout fl_pw;
    @BindView(R.id.bt_loginActivity_login)
    Button bt_loginActivity_login;
    @BindView(R.id.et_loginActivity_mobile)
    EditText et_loginActivity_mobile;
    @BindView(R.id.et_loginActivity_code)
    EditText et_loginActivity_code;
    @BindView(R.id.et_loginActivity_account)
    EditText et_loginActivity_account;
    @BindView(R.id.et_loginActivity_pw)
    EditText et_loginActivity_pw;
    @BindView(R.id.tv_loginActivity_getCode)
    TextView tv_loginActivity_getCode;
    @BindView(R.id.tv_loginActivity_protocol)
    TextView tv_loginActivity_protocol;
    @BindView(R.id.tv_loginActivity_policy)
    TextView tv_loginActivity_policy;

    private String loginType="1";
    private String rid;

    @BindView(R.id.cb_agree)
    CheckBox cbAgree;

    @BindView(R.id.tv_join_wanli)
    TextView tvJoinWanli;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {
        et_loginActivity_pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
        initLoginType("1");
        startService();
        checkBtnState();
        et_loginActivity_mobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                checkBtnState();
            }
        });
        et_loginActivity_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                checkBtnState();
            }
        });
        et_loginActivity_account.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                checkBtnState();
            }
        });
        et_loginActivity_pw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                checkBtnState();
            }
        });
//        cbAgree.setOnCheckedChangeListener(onCheckedChangeListener);

    }

    /*阅读协议是否勾选选项*/
//    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
//        @Override
//        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//            if (buttonView.getId() == R.id.cb_agree) {
//                bt_loginActivity_login.setEnabled(isChecked);
//            }
//        }
//    };

    @Override
    public void initEvent() {}

    @Override
    protected void onResume() {
        super.onResume();
    }


    @OnClick({R.id.bt_loginActivity_login,R.id.fl_phone,R.id.fl_pw,R.id.tv_loginActivity_getCode,R.id.tv_loginActivity_protocol,R.id.tv_loginActivity_policy,R.id.tv_join_wanli})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_loginActivity_login:
                if (cbAgree.isChecked()){
                    login();  
                }else {
                    Toast.makeText(LoginActivity.this, "请先阅读并同意协议", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.fl_phone:
                initLoginType("1");
                break;
            case R.id.fl_pw:
                initLoginType("2");
                break;
            case R.id.tv_loginActivity_getCode:
                checkToGetValidCode();
                break;
            case R.id.tv_loginActivity_protocol:
                toProtocol();
                break;
            case R.id.tv_loginActivity_policy:
                toPolicy();
                break;
            case R.id.tv_join_wanli:
                IntentUtil.goJoinWanliActivity(LoginActivity.this);
                break;
            default:
                break;
        }
    }

    private void toProtocol(){
        Intent intent = new Intent(mActivity,WebActivity.class);
        intent.putExtra("purl", Constants.protocolUrl);
        startActivity(intent);
    }

    private void toPolicy(){
        Intent intent = new Intent(mActivity,WebActivity.class);
        intent.putExtra("purl", Constants.privateUrl);
        startActivity(intent);
    }


    //登录方式切换
    public void initLoginType(String type){
        if("1".equals(type)){
            loginType="1";
            ll_phone.setVisibility(View.VISIBLE);
            ll_pw.setVisibility(View.INVISIBLE);
            tv_phone_b.setVisibility(View.VISIBLE);
            tv_pw_b.setVisibility(View.INVISIBLE);
        }
        if("2".equals(type)){
            loginType="2";
            ll_phone.setVisibility(View.INVISIBLE);
            ll_pw.setVisibility(View.VISIBLE);
            tv_phone_b.setVisibility(View.INVISIBLE);
            tv_pw_b.setVisibility(View.VISIBLE);
        }
        checkBtnState();
    }

    //获取验证码
    public void checkToGetValidCode(){
        if(!isValidPhone(et_loginActivity_mobile.getText().toString())) return;
        getValidCode();
    }

    private boolean isValidAccount(String account) {
        if (TextUtils.isEmpty(account)){
            Toast.makeText(this,"请输入账号",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean isValidPw(String pw){
        if (TextUtils.isEmpty(pw)){
            Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean isValidPhone(String phone) {
        if (TextUtils.isEmpty(phone)){
            Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!phone.matches(Constant.PHONE_PATTERN)){
            Toast.makeText(this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean isValidVCode(String vcode){
        if (TextUtils.isEmpty(vcode)){
            Toast.makeText(this,"请输入验证码",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    public void login(){
        if("1".equals(loginType)){
            if(!isValidPhone(et_loginActivity_mobile.getText().toString())) return;
            if(!isValidVCode(et_loginActivity_code.getText().toString())) return;
            loginByPhone();
        }else{
            if(!isValidAccount(et_loginActivity_account.getText().toString())) return;
            if(!isValidPw(et_loginActivity_pw.getText().toString())) return;
            loginByPw();
        }
    }

    //验证码登录
    public void loginByPhone(){
        final Map<String, String> map = new HashMap<>();
        map.put("mobile", et_loginActivity_mobile.getText().toString());
        map.put("validateCode", et_loginActivity_code.getText().toString());
        Logger.i(TAG, JSON.toJSONString(map));
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .loginByPhone(JSON.toJSONString(map))
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i("----"+response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                ServerResponse serverResponse=JSON.parseObject(response,ServerResponse.class);
                if("1000".equals(rCode)) {
                    Toast.makeText(mContext,"验证码登录成功",Toast.LENGTH_SHORT).show();
                    SPUtil.put("phone",et_loginActivity_mobile.getText().toString());
                    AccountManager.setUserLogin(true);
                    EventBus.getDefault().post(new UpdateUserInfoEvent());
                    EventBus.getDefault().post(new RefreshHomePageEvent());
                    UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                    updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
                    updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                    updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                    updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                    EventBus.getDefault().post(updateProductListEvent);
                    getAgentDetail();
                    toFinishActivity();
                }else if("2004".equals(rCode)) {
                    Toast.makeText(mActivity, serverResponse.getMsg(), Toast.LENGTH_SHORT).show();
                }else  {
                    Toast.makeText(mActivity, serverResponse.getData(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"登录失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }



    //密码登录
    public void loginByPw(){
        final Map<String, String> map = new HashMap<>();
        map.put("mobile", et_loginActivity_account.getText().toString());
        map.put("password", et_loginActivity_pw.getText().toString());
        Logger.i(TAG, JSON.toJSONString(map));
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .loginByPw(JSON.toJSONString(map))
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i("loginByPw---"+ response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                String rData  = jsonObject.getString("data");
                if("1000".equals(rCode)) {
                    Toast.makeText(mContext,"密码登录成功",Toast.LENGTH_SHORT).show();
                    SPUtil.put("phone",et_loginActivity_account.getText().toString());
                    AccountManager.setUserLogin(true);
                    EventBus.getDefault().post(new UpdateUserInfoEvent());
                    EventBus.getDefault().post(new RefreshHomePageEvent());
                    UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                    updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
                    updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                    updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                    updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                    EventBus.getDefault().post(updateProductListEvent);
                    getAgentDetail();
                    toFinishActivity();
                }else {
                    Toast.makeText(mActivity, rData, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"登录失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }



    //获取代理人信息
    public void getAgentDetail(){
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .getAgentDetail()
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                   saveAgentInfo(jsonObject);
                }else {
                    Toast.makeText(mActivity, rMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mActivity,"获取代理人信息失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    //保存代理人信息 "data":{"name":"周昕宸","workNo":"60004","image":"https://ceshi.wanlibaoxian.com:444/agentImage/2021/10/09/F1142021100916534165219091532364256624.jpg","loginPwdFlag":"Y","mobile":"13642040397"}}
    private void saveAgentInfo(JSONObject json){
        JSONObject agent = JSON.parseObject(json.getString("data"));
        String name = agent.getString("name");
        String workNo = agent.getString("workNo");
        String image = agent.getString("image");
        String loginPwdFlag = agent.getString("loginPwdFlag");
        String mobile = agent.getString("mobile");
        AgentBean ab = new AgentBean();
        ab.setAccessToken((String)SPUtil.get("Access-Token", ""));
        ab.setPublicKey((String)SPUtil.get("Public-Key",""));
        ab.setName(name);
        ab.setWorkNo(workNo);
        ab.setImage(image);
        ab.setLoginPwdFlag(loginPwdFlag);
        ab.setMobile(mobile);
        SPUtil.putBean(Constant.USER_INFO,"agent",ab);

//        Logger.i(JSON.toJSONString(ab));
        Logger.i(JSON.toJSONString(SPUtil.getBean(Constant.USER_INFO,"agent")));
    }

    //成功登录关闭当前页面
    public void toFinishActivity(){
//        Intent intent = new Intent(this,MainActivity.class);
            finish();
//            intent.putExtra("to","0");
//            startActivity(intent);
    }
    //获取验证码
    public void getValidCode(){
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .getValidCode(et_loginActivity_mobile.getText().toString())
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    timer.start();
                    tv_loginActivity_getCode.setEnabled(false);
                    Toast.makeText(mContext,"获取验证码成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"获取验证码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void startService(){
        Intent intent = new Intent("com.wlbx.agent.util.fingerprint.JudgeFingureService");
        intent.setPackage(getPackageName());
        startService(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish();
            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 校验当前用户是否登录
     */
    public boolean checkLogin(){
        if(!"".equals(SPUtil.get("phone",""))){
            return true;
        }else{
            return false;
        }
    }

    /*
     *标识状态
     */
    public void checkBtnState(){
        if("1".equals(loginType)){
            if("".equals(et_loginActivity_mobile.getText().toString()) || "".equals(et_loginActivity_code.getText().toString())){
                bt_loginActivity_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_dis));
                bt_loginActivity_login.setEnabled(false);
            }else{
                bt_loginActivity_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_en));
                bt_loginActivity_login.setEnabled(true);
            }
        }else{
            if("".equals(et_loginActivity_account.getText().toString()) || "".equals(et_loginActivity_pw.getText().toString())){
                bt_loginActivity_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_dis));
                bt_loginActivity_login.setEnabled(false);
            }else{
                bt_loginActivity_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_en));
                bt_loginActivity_login.setEnabled(true);
            }
        }
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            if (tv_loginActivity_getCode!=null){
                tv_loginActivity_getCode.setTextColor(getResources().getColor(R.color.color_gray));
                tv_loginActivity_getCode.setText("重新获取"+millisUntilFinished/1000 + "S");
            }

        }

        @Override
        public void onFinish() {
            if (tv_loginActivity_getCode!=null){
            tv_loginActivity_getCode.setEnabled(true);
            tv_loginActivity_getCode.setTextColor(getResources().getColor(R.color.big_color));
            tv_loginActivity_getCode.setText("重新获取");}
        }
    };

}